package com.ui;

import com.service.ClassService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AddClassDialog extends JFrame {
    private JTextField classNameField;
    private ClassService classService; // 假设您已经创建了ClassService类

    public AddClassDialog(ClassService classService) {
        this.classService = classService; // 注入ClassService依赖
        setTitle("添加班级");
        setSize(300, 150);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示

        // 创建面板和组件
        JPanel panel = new JPanel();
        classNameField = new JTextField(20);
        JButton addButton = new JButton("添加");
        JButton backButton = new JButton("返回");

        // 添加组件到面板
        panel.add(new JLabel("班级名称:"));
        panel.add(classNameField);
        panel.add(addButton);
        panel.add(backButton);

        // 添加面板到窗口
        add(panel);

        // 添加按钮的事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String className = classNameField.getText();
                if (className.isEmpty()) {
                    JOptionPane.showMessageDialog(AddClassDialog.this, "班级名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                try {
                    classService.addClass(className);
                    JOptionPane.showMessageDialog(AddClassDialog.this, "班级添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose(); // 关闭窗口
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(AddClassDialog.this, "班级添加失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
            }
        });
    }
}